package lapsnake.ui;

import java.awt.Color;
import java.awt.Composite;
import java.awt.CompositeContext;
import java.awt.RenderingHints;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class BlendComposite implements Composite
{
	private int r, g, b;
	public BlendComposite(Color c)
	{
		r = c.getRed();
		g = c.getGreen();
		b = c.getBlue();
	}
	@Override
	public CompositeContext createContext(ColorModel srcColorModel,
		ColorModel dstColorModel, RenderingHints hints)
	{
		return new CompositeContext()
		{
			@Override
			public void dispose() {}
			
			@Override
			public void compose(Raster src, Raster dstIn, WritableRaster dstOut)
			{
				int sx = src.getMinX();
				int sy = src.getMinY();
				int w = src.getWidth();
				int h = src.getHeight();
				int[] s = new int[w*h*4];
				src.getPixels(sx, sy, w, h, s);
				assert src.getNumBands() == 4;
				
				int dx = dstIn.getMinX();
				int dy = dstIn.getMinY();
				assert dstIn.getWidth() == w;
				assert dstIn.getHeight() == h;
				assert dstOut.getWidth() == w;
				assert dstOut.getHeight() == h;
				assert dstOut.getMinX() == dx;
				assert dstOut.getMinY() == dy;
				int outBands = dstIn.getNumBands();
				int[] d = new int[w*h*outBands];
				dstIn.getPixels(dx, dy, w, h, d);
				
				assert dstIn.getNumBands() == outBands;
				
				for(int i = 0; i<w*h; i += 1)
				{
					int a = s[i*4+3];
					d[i*outBands  ] = (d[i*outBands  ]*(0xFF-a))/0xFF + (s[i*4  ]*a*r)/0xFFFF;
					d[i*outBands+1] = (d[i*outBands+1]*(0xFF-a))/0xFF + (s[i*4+1]*a*g)/0xFFFF;
					d[i*outBands+2] = (d[i*outBands+2]*(0xFF-a))/0xFF + (s[i*4+2]*a*b)/0xFFFF;
					if(outBands == 4)
						d[i*4+3] = a + ((0xFF-a)*d[i*4+3])/0xFF;
				}
				
				dstOut.setPixels(dx, dy, w, h, d);
			}
		};
	}
}
